package com.atguigu.smsservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.smsservice.service.SmsService;
import com.atguigu.smsservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信发送")
@CrossOrigin
@RestController
@RequestMapping("/edusms/sms")
public class SmsApiController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @ApiOperation(value = "短信发送")
    @GetMapping("sendSmsPhone/{phone}")
    public R send(@PathVariable String phone) {
        /*
        1.拿到手机号查验证码
        2.验证是否存在，直接返回ok
        3.验证码不存在生成验证码
        4.调用接口发送验证码
        5.将验证码存入redis
         */
        String rPhone = redisTemplate.opsForValue().get(phone);
        if (rPhone != null) {
            return R.ok();
        }
        String code = RandomUtil.getFourBitRandom();
        Map<String,String> map=new HashMap<>();
        map.put("code","code");
        boolean isSend = smsService.sendSmsPhone(phone,map);
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5 ,TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error();
        }


    }
}
